<template>
  <div class="system-edit-user-container">
    <el-dialog
        :title="(ruleForm.id!==0?'修改':'添加')+'微件'"
        v-model="isShowDialog"
        width="800">
      <div v-if="ruleForm.type != ''" style="margin-bottom: 20px; max-width: 400px;margin-left: 150px;">
        <component :is="ruleForm.type + 'Widget'" :edit-data="renderForm" :is-edit="true" :key="autoKey"></component>
      </div>
      <el-form ref="formRef" :model="ruleForm" :rules="rules" size="default" label-position="top">
        <el-row :gutter="30">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <p class="mb10">#ID&nbsp;&nbsp;<b>{{ ruleForm.id }}</b></p>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="标识名" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入名称" clearable @change="refreshAutoKey"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="微件类型" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择" clearable class="w100" @change="handleTypeChange">
                <el-option
                    v-for="type in types"
                    :key="'t-'+type.value"
                    :label="type.label"
                    :value="type.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="API接口" prop="api">
              <el-input v-model="ruleForm.api" placeholder="请输入API接口" @change="refreshAutoKey"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="图标选择" prop="selectIcon">
              <IconSelector placeholder="请输入菜单图标" v-model="selectIcon" type="all"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="微件样式" prop="style">
              <el-input v-model="ruleForm.styles" type="textarea" :autosize="{ minRows: 10, maxRows: 15 }"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="数据格式" prop="data">
              <el-input v-model="ruleForm.data" type="textarea" :autosize="{ minRows: 10, maxRows: 15 }"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit"
                     size="default">{{ ruleForm.id !== 0 ? '修 改' : '添 加' }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {reactive, toRefs, onMounted, defineComponent, ref, unref, watch} from 'vue';
import {ElMessage} from "element-plus";
import {WidgetTypes, WidgetList} from "/src/components/widget/widget";
import {addWidget, getWidget, updateWidget} from "/@/api/system/widget";
import cardWidget from "/@/components/widget/cardWidget.vue";
import IconSelector from "/@/components/iconSelector/index.vue";

export default defineComponent({
  name: 'systemEditWidget',
  components: {cardWidget, IconSelector},
  props: {
    genderData: {
      type: Array,
      default: () => []
    }
  },
  setup(prop, {emit}) {
    const autoKey = ref('374982375');
    const formRef = ref<HTMLElement | null>(null);
    const state = reactive({
      isShowDialog: false,
      types: WidgetTypes,
      widgetList: WidgetList,
      selectIcon: '',
      ruleForm: {
        id: 0,
        name: '',
        type: 'card',
        styles: '',
        data: '',
        api: ''
      },
      renderForm: {},
      //表单校验
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
      }
    });
    // 打开弹窗
    const openDialog = (row?: any) => {
      resetForm();
      if (row) {
        getWidget({id: row.id}).then((res: any) => {
          const _data = res.data;
          const _styles = _data.styles == null ? state.widgetList[_data.type].styles : _data.styles;
          state.ruleForm = {
            id: _data.id,
            name: _data.name,
            type: _data.type,
            styles: JSON.stringify(_styles),
            data: _data.data == null ? JSON.stringify(state.widgetList[_data.type].data) : JSON.stringify(_data.data),
            api: _data.api,
          };
          state.selectIcon = _styles.icon
        })
      }
      state.isShowDialog = true;
    };
    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    watch(
        () => [state.selectIcon, state.ruleForm],
        (val, old) => {
          let _style = JSON.parse(state.ruleForm.styles) || {}
          _style.icon = val[0]
          state.ruleForm.styles = JSON.stringify(_style)
          refreshAutoKey();
          let _form = JSON.parse(JSON.stringify(val[1]))
          _form.styles = JSON.parse(state.ruleForm.styles)
          _form.data = JSON.parse(state.ruleForm.data)
          state.renderForm = _form;
        }
    );
    // 新增
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        let _form = state.ruleForm
        // _form.styles = _form.styles
        // _form.data = _form.data
        if (valid) {
          if (_form.id === 0) {
            //添加
            addWidget(_form).then(() => {
              ElMessage.success('微件添加成功');
              closeDialog(); // 关闭弹窗
              emit('callback')
            });
          } else {
            //修改
            updateWidget(_form).then(() => {
              ElMessage.success('微件修改成功');
              closeDialog(); // 关闭弹窗
              emit('callback')
            });
          }
        }
      });
    };
    // 页面加载时
    onMounted(() => {
      // initTableData();
    });
    const resetForm = () => {
      const _styles = state.widgetList.card.styles
      state.ruleForm = {
        id: 0,
        name: '',
        type: 'card',
        styles: JSON.stringify(_styles),
        data: JSON.stringify(state.widgetList.card.data),
        api: ''
      }
      state.selectIcon = _styles.icon
    };
    const handleTypeChange = (val) => {
      if (state.ruleForm.styles == null) {
        state.ruleForm.styles = JSON.stringify(state.widgetList[val].styles);
      }
      if (state.ruleForm.data == null) {
        state.ruleForm.data = JSON.stringify(state.widgetList[val].data);
      }
    }
    const refreshAutoKey = () => {
      autoKey.value = new Date().getTime() + (Math.random() * 1000).toFixed(0);
    };
    return {
      autoKey,
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,
      formRef,
      refreshAutoKey,
      handleTypeChange,
      ...toRefs(state),
    };
  },
});
</script>
